using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

using Autodesk.Connectivity.WebServices;
using Autodesk.Connectivity.WebServicesTools;
using Autodesk.Connectivity.Explorer.Extensibility;
using Autodesk.Connectivity.Extensibility.Framework;


namespace EffectiveFolderPermissions
{


    public partial class MainForm : Form
    {





        private WebServiceManager webSericeManager;
        private VaultContext vaultContext;


        // This lists all users in a group, N levels deep
        // The group ID is the key and the value is a list of user IDs
        // For easy of use, users will also be added.  Key = userId, Value = userId
        private Dictionary<long, List<long>> m_groupMembership;

        // This stores all the effective ACLs for each folder
        // the folder ID is the key and the ACL is the value
        private Dictionary<long, ACL> m_folderACLs;

        private List<_Folder> m_folders;
        private List<_UserInfo> m_users;
        private List<_GroupInfo> m_groups;

        // Maps the user ID to the UserInfo object
        private Dictionary<long, _UserInfo> m_userMap;
        private Dictionary<long, _GroupInfo> m_groupMap;

        // Maps the role ID to permissions
        private Dictionary<long, Permis[]> m_permissionMap;

        private Settings m_settings;
        private DateTime startDate = DateTime.Now;


        private Permissions p = null;
        private long folderIdToModify;
        private ACE[] newACE;

        private bool allowedToClick = true;

        // a list of all groups
        GroupInfo[] m_groupInfos;

        public List<_UserInfo> Users
        {
            get { return m_users; }
        }
        public List<_GroupInfo> Groups
        {
            get { return m_groups; }
        }
        /// <summary>
        /// Display the effective folder permissions on a set of folders determined
        /// by the settings.
        /// </summary>
        public MainForm(WebServiceManager wsm, VaultContext vc)
        {
            webSericeManager = wsm;
            vaultContext = vc;
            Init(false, -1);
        }

        /// <summary>
        /// Display the effective folder permissions on a specific folder.
        /// </summary>
        /// <param name="folderId">The folder to get permissions on.</param>
        public MainForm(long folderId, WebServiceManager wsm, VaultContext vc )
        {   
            
            webSericeManager = wsm;
            vaultContext = vc;
            Init(true, folderId);
            
        }

        private void Init(bool singleFolderMode, long folderId)
        {
            InitializeComponent();

            m_settings = Settings.LoadSettings(webSericeManager);

            if (rbtnGroups.Checked == true)
                GatherGroupMembership();
            else if (rbtnUsers.Checked == true)
                GatherUserGroupMembership();
            

            if (!singleFolderMode)
                GatherFolders();
            else
            {
                m_folders = new List<_Folder>();
                DocumentService docSvc = webSericeManager.DocumentService;
                Folder folder = docSvc.GetFolderById(folderId);
                m_folders.Add(_Folder.Convert(folder));
            }

            GatherACLs();
            m_folders.Sort();
            
            if (rbtnGroups.Checked == true)
               m_groups.Sort();
            else if (rbtnUsers.Checked == true)
               m_users.Sort();
            

            InitGrid();
            FillGrid();

            m_noAccessPictureBox.Image = Util.NO_ACCESS_ICON.ToBitmap();
            m_fulControlPictureBox.Image = Util.FULL_ACCESS_ICON.ToBitmap();
            m_readOnlyPictureBox.Image = Util.READ_ICON.ToBitmap();
            m_readWritePictureBox.Image = Util.READ_WRITE_ICON.ToBitmap();
        }

        private void InitGrid()
        {
            foreach (Folder folder in m_folders)
            {
                DataGridViewImageColumn imageColumn = new DataGridViewImageColumn(true);
                imageColumn.HeaderText = folder.FullName;
                imageColumn.Name = folder.Id.ToString();
                imageColumn.Width = 20;

                m_outputGrid.Columns.Add(imageColumn);
            }

            m_outputGrid.ColumnHeadersHeight = 200;
        }

        private void ResetGrid()
        {

            m_outputGrid.RowCount = 0;

        }

        private void FillGrid()
        {
            ACL [] acls = new ACL[m_outputGrid.Columns.Count];
            for (int i = 0; i < acls.Length; i++)
            {
                long folderId = long.Parse(m_outputGrid.Columns[i].Name);
                if (m_folderACLs.ContainsKey(folderId))
                    acls[i] = m_folderACLs[folderId];
                else
                    acls[i] = null;
            }

            string vaultName = vaultContext.VaultName;

            if (rbtnGroups.Checked == true)
            {
                FillGridGroups(vaultName, acls);

            }
            else if (rbtnUsers.Checked == true)
            {
                FillGridUsers(vaultName, acls);
            }


           
        }

        private void UpdateCell()
        {
            ACL acl = new ACL();
        }



        private void FillGridUsers(string vaultName, ACL[] acls)
        {
            foreach (_UserInfo user in m_users)
            {
                object[] rowData = new object[m_outputGrid.Columns.Count];

                bool hasVaultAccess = false;
                foreach (KnowledgeVault vault in user._Vaults)
                {
                    if (String.Compare(vault.Name, vaultName, true) == 0)
                    {
                        hasVaultAccess = true;
                        break;
                    }
                }

                for (int i = 0; i < rowData.Length; i++)
                {
                    // if the user is inactive, then they are shown as having no access to all folders
                    if (!user.User.IsActive)
                    {
                        rowData[i] = Util.GetGridValue(PermissionState.NO_ACCESS);
                        continue;
                    }

                    // if the user doesn't have vault access, then they are shown as having no access to all folders
                    if (!hasVaultAccess)
                    {
                        rowData[i] = Util.GetGridValue(PermissionState.NO_ACCESS);
                        continue;
                    }

                    if (acls[i] == null)
                    {
                        // null ACL means access is allowed based on permissions
                        rowData[i] = Util.GetGridValue(Util.DecodePermissions(user));
                    }
                    else
                    {
                        _ACE userAce = null;
                        foreach (_ACE ace in acls[i].ACEArray)
                        {
                            if (ace.UserGrpId == user.User.Id)
                            {
                                userAce = ace;
                                break;
                            }
                        }

                        if (userAce == null)
                        {
                            // no data was found on the user, which means no access
                            if (!user._IsAdmin)
                                rowData[i] = Util.GetGridValue(PermissionState.NO_ACCESS);
                            else
                                rowData[i] = Util.GetGridValue(PermissionState.READ_ONLY);
                        }
                        else
                        {
                            rowData[i] = Util.GetGridValue(Util.DecodePermissions(userAce._Permissions, user));
                        }
                    }

                }

                int index = m_outputGrid.Rows.Add(rowData);
                m_outputGrid.Rows[index].HeaderCell.Value = user.User.Name;
            }

        }


        private void FillGridGroups(string vaultName, ACL[] acls)
        {
            foreach (_GroupInfo group in m_groups)
            {
                object[] rowData = new object[m_outputGrid.Columns.Count];

                bool hasVaultAccess = false;
                foreach (KnowledgeVault vault in group._Vaults)
                {
                    if (String.Compare(vault.Name, vaultName, true) == 0)
                    {
                        hasVaultAccess = true;
                        break;
                    }
                }

                for (int i = 0; i < rowData.Length; i++)
                {
                    // if the user is inactive, then they are shown as having no access to all folders
                    if (!group.Group.IsActive)
                    {
                        rowData[i] = Util.GetGridValue(PermissionState.NO_ACCESS);
                        continue;
                    }

                    // if the user doesn't have vault access, then they are shown as having no access to all folders
                    if (!hasVaultAccess)
                    {
                        rowData[i] = Util.GetGridValue(PermissionState.NO_ACCESS);
                        continue;
                    }

                    if (acls[i] == null)
                    {
                        // null ACL means access is allowed based on permissions
                        rowData[i] = Util.GetGridValue(Util.DecodePermissions(group));
                    }
                    else
                    {
                        _ACE groupAce = null;
                        foreach (_ACE ace in acls[i].ACEArray)
                        {
                            if (ace.UserGrpId == group.Group.Id)
                            {
                                groupAce = ace;
                                break;
                            }
                        }

                        if (groupAce == null)
                        {
                            // no data was found on the user, which means no access
                            if (!group._IsAdmin)
                                rowData[i] = Util.GetGridValue(PermissionState.NO_ACCESS);
                            else
                                rowData[i] = Util.GetGridValue(PermissionState.READ_ONLY);
                        }
                        else
                        {
                            rowData[i] = Util.GetGridValue(Util.DecodePermissions(groupAce._Permissions, group));
                        }
                    }

                }

                int index = m_outputGrid.Rows.Add(rowData);
                m_outputGrid.Rows[index].HeaderCell.Value = group.Group.Name;
            }


        }

        private void GatherACLs()
        {
            if (m_folders == null || m_folders.Count == 0)
                return;

            if (m_groupMembership == null || m_groupMembership.Count == 0)
                return;

            SecurityService secSvc = webSericeManager.SecurityService;// (SecurityService)ServiceManager.GetService("SecurityService");

            List<long> folderIds = new List<long>();
            foreach (Folder f in m_folders)
            {
                folderIds.Add(f.Id);
            }

            m_folderACLs = new Dictionary<long, ACL>();
            ACL[] acls = null;
            try
            {
                acls = secSvc.GetACLsByEntityIds(folderIds.ToArray());
            }
            catch
            {
                // this will fail for base Vault, so we will ignore the error
            }

            if (acls != null)
            {
                for (int i = 0; i < acls.Length; i++)
                {
                    if (acls[i] == null)
                        continue;

                    ACL effAcl = CalculateEffectiveACL(acls[i]);
                    m_folderACLs.Add(folderIds[i], effAcl);
                }
            }
        }

        // replace all group entries, with the users.
        private ACL CalculateEffectiveACL(ACL acl)
        {
            ACL retval = new ACL();
            retval.Id = acl.Id;

            Dictionary<long, _ACE> newACEs = new Dictionary<long, _ACE>();
            foreach (ACE ace in acl.ACEArray)
            {
                if (!m_groupMembership.ContainsKey(ace.UserGrpId))
                    continue;  // we should not hit this code

                // for each ACE, create a set of new ACEs, one for each group member
                List<long> memberIds = m_groupMembership[ace.UserGrpId];
                foreach (long memberId in memberIds)
                {
                    _ACE newACE = new _ACE();
                    newACE.UserGrpId = memberId;
                    newACE._Permissions = Util.ConvertPermissions(ace.PermisArray);
                    newACE.PermisArray = null; // _Permissions is much easier to use
                    Util.AddAceToMap(newACE, newACEs);
                }
            }

            ACE[] aces = new ACE[newACEs.Count];
            int i = 0;
            
            foreach (ACE ace in newACEs.Values)
            {
                aces[i] = ace;
                i++;
            }

            retval.ACEArray = aces;
            return retval;
        }

        private void GatherFolders()
        {
            m_folders = new List<_Folder>();
            DocumentService docSvc = webSericeManager.DocumentService;

            Folder root = docSvc.GetFolderRoot();
            m_folders.Add(_Folder.Convert(root));

            // It's usually faster to make fewer web service calls
            // so let's get all folders from Vault and prune out the ones we don't want to display
            Folder[] folders = docSvc.GetFoldersByParentId(root.Id, true);
            if (folders != null)
            {
                foreach (Folder folder in folders)
                {
                    bool skip = false;
                    foreach (string exclude in m_settings.ExcludedFolders)
                    {
                        if (folder.FullName.StartsWith(exclude, StringComparison.CurrentCultureIgnoreCase))
                            skip = true;
                    }
                    if (skip)
                        continue;

                    if (Util.GetDepth(folder) <= m_settings.FolderDepth)
                        m_folders.Add(_Folder.Convert(folder));
                    else if (m_settings.IncludedFolders.Contains(folder.FullName))
                        m_folders.Add(_Folder.Convert(folder));
                }
            }  
        }

        

        /// <summary>
        /// Gets all users and groups in the Vault
        /// </summary>
        private void GatherUserGroupMembership()
        {
            m_groupMembership = new Dictionary<long, List<long>>();
            m_users = new List<_UserInfo>();
            m_userMap = new Dictionary<long, _UserInfo>();

            AdminService adminSvc = webSericeManager.AdminService;

            // get permissions
            m_permissionMap = new Dictionary<long, Permis[]>();
            Role[] roles = null;
            try
            {
               roles = adminSvc.GetAllRoles();
            }
            catch
            {
                // I'm going to be lazy and assume that the reason for the error is because the user is not an admin
                throw new Exception("Cannot read user/group information.  Make sure you are logging in as an administrator.");
            }

            foreach (Role role in roles)
            {
                Permis[] permissions = adminSvc.GetPermissionsByRoleId(role.Id);
                m_permissionMap.Add(role.Id, permissions);
            }


            Group [] groups = adminSvc.GetAllGroups();
            List<long> groupIds = new List<long>(groups.Length);
            foreach (Group group in groups)
            {
                if (group.IsActive)
                    groupIds.Add(group.Id);
            }
            m_groupInfos = adminSvc.GetGroupInfosByGroupIds(groupIds.ToArray());

            User [] tmpusers = adminSvc.GetAllUsers();
            List<long> userIds = new List<long>(tmpusers.Length);
            foreach (User u in tmpusers)
            {
                if (m_settings.ShowInactiveUsers || u.IsActive)
                    userIds.Add(u.Id);
            }
            
            _UserInfo[] users = _UserInfo.Convert(adminSvc.GetUserInfosByUserIds(userIds.ToArray()));

            foreach (_UserInfo u in users)
            {
                if (u.Vaults != null)
                    u._Vaults.AddRange(u.Vaults);
                m_userMap.Add(u.User.Id, u);

                roles = u.Roles;
                if (roles != null)
                {
                    List<long> permissionsList = new List<long>();
                    foreach (Role role in roles)
                    {
                        Util.AddPermissionsToList(permissionsList, m_permissionMap[role.Id]);
                    }
                    Util.SetUserPermissions(u, permissionsList);
                }

                // We are going to treat each user as a group with only themselves as the member
                // trust me, this will make things easier later on
                List<long> membership = new List<long>();
                membership.Add(u.User.Id);

                m_groupMembership.Add(u.User.Id, membership);
            }

            foreach (GroupInfo groupInfo in m_groupInfos)
            {
                AddGroupMembership(groupInfo, new List<long>());
            }

            

            if (m_settings.ShowUsersWithoutVaultAccess)
                m_users.AddRange(users);
            else
            {
                foreach (_UserInfo user in users)
                {
                    bool hasVaultAccess = false;
                    foreach (KnowledgeVault vault in user._Vaults)
                    {
                        if (String.Compare(vault.Name, vaultContext.VaultName, true) == 0)
                        {
                            hasVaultAccess = true;
                            break;
                        }
                    }

                    if (hasVaultAccess)
                        m_users.Add(user);
                }
            }
        }

        /// <summary>
        /// Gets all users and groups in the Vault
        /// </summary>
        private void GatherGroupMembership()
        {
            m_groupMembership = new Dictionary<long, List<long>>();
            m_groups = new List<_GroupInfo>();
            m_groupMap = new Dictionary<long, _GroupInfo>();

            AdminService adminSvc = webSericeManager.AdminService;


            // get permissions
            m_permissionMap = new Dictionary<long, Permis[]>();
            Role[] roles = null;
            try
            {
                roles = adminSvc.GetAllRoles();
            }
            catch
            {
                // I'm going to be lazy and assume that the reason for the error is because the user is not an admin
                throw new Exception("Cannot read user/group information.  Make sure you are logging in as an administrator.");
            }

            foreach (Role role in roles)
            {
                Permis[] permissions = adminSvc.GetPermissionsByRoleId(role.Id);
                m_permissionMap.Add(role.Id, permissions);
            }


            Group[] tempgroups = adminSvc.GetAllGroups();
            List<long> groupIds = new List<long>(tempgroups.Length);
            foreach (Group group in tempgroups)
            {
                if (group.IsActive)
                    groupIds.Add(group.Id);
            }
            m_groupInfos = adminSvc.GetGroupInfosByGroupIds(groupIds.ToArray());

            //User[] tmpusers = adminSvc.GetAllUsers();
            //List<long> userIds = new List<long>(tmpusers.Length);
            //foreach (User u in tmpusers)
            //{
            //    if (m_settings.ShowInactiveUsers || u.IsActive)
            //        userIds.Add(u.Id);
            //}

            _GroupInfo[] groups = _GroupInfo.Convert(adminSvc.GetGroupInfosByGroupIds(groupIds.ToArray()));

            foreach (_GroupInfo g in groups)
            {
                if (g.Vaults != null)
                    g._Vaults.AddRange(g.Vaults);
                m_groupMap.Add(g.Group.Id, g);

                roles = g.Roles;
                if (roles != null)
                {
                    List<long> permissionsList = new List<long>();
                    foreach (Role role in roles)
                    {
                        Util.AddPermissionsToList(permissionsList, m_permissionMap[role.Id]);
                    }
                    Util.SetGroupPermissions(g, permissionsList);
                }

                // We are going to treat each user as a group with only themselves as the member
                // trust me, this will make things easier later on
                List<long> membership = new List<long>();
                membership.Add(g.Group.Id);

                m_groupMembership.Add(g.Group.Id, membership);
            }



            if (m_settings.ShowUsersWithoutVaultAccess)
                m_groups.AddRange(groups);
            else
            {
                foreach (_GroupInfo group in groups)
                {
                    bool hasVaultAccess = false;
                    foreach (KnowledgeVault vault in group._Vaults)
                    {
                        if (String.Compare(vault.Name, vaultContext.VaultName, true) == 0)
                        {
                            hasVaultAccess = true;
                            break;
                        }
                    }

                    if (hasVaultAccess)
                        m_groups.Add(group);
                }
            }
        }
        private void AddGroupMembership(GroupInfo groupInfo, List<long> parentPermissions)
        {
            List<long> membership = new List<long>();

            // add this groups roles to the list
            List<long> permissions = new List<long>(parentPermissions);
            Role[] roles = groupInfo.Roles;
            if (roles != null)
            {
                foreach (Role role in roles)
                {
                    Util.AddPermissionsToList(permissions, m_permissionMap[role.Id]);
                }
            }

            // add in the membership of the sub groups
            if (groupInfo.Groups != null)
            {
                foreach (Group subGroup in groupInfo.Groups)
                {
                    if (!subGroup.IsActive)
                        continue;

                    AddGroupMembership(GetGroupInfo(subGroup.Id), permissions);

                    List<long> subMembership = m_groupMembership[subGroup.Id];

                    Util.AddListToList(subMembership, membership);
                }
            }

            // add in the direct user membership
            if (groupInfo.Users != null)
            {
                foreach (User user in groupInfo.Users)
                {
                    Util.AddItemToList(user.Id, membership);
                    AddVaultsToUser(user.Id, groupInfo.Vaults);

                    if (m_userMap.ContainsKey(user.Id))
                    {
                        _UserInfo u = m_userMap[user.Id];
                        Util.SetUserPermissions(u, permissions);
                    } 
                }
            }

            // here we should have a list of all user members N levels deep in the group
            if (!m_groupMembership.ContainsKey(groupInfo.Group.Id))
                m_groupMembership.Add(groupInfo.Group.Id, membership);
            else
            {
                List<long> existingMembership = m_groupMembership[groupInfo.Group.Id];
                Util.AddListToList(existingMembership, membership);
                m_groupMembership[groupInfo.Group.Id] = membership;
            }
        }

        private void AddVaultsToUser(long userId, KnowledgeVault[] vaults)
        {
            if (vaults == null)
                return;

            if (m_userMap.ContainsKey(userId))
            {
                _UserInfo user = m_userMap[userId];

                foreach (KnowledgeVault vault in vaults)
                {
                    if (!user._Vaults.Contains(vault))
                        user._Vaults.Add(vault);
                }
            }
        }

        private GroupInfo GetGroupInfo(long groupId)
        {
            foreach (GroupInfo groupInfo in m_groupInfos)
            {
                if (groupInfo.Group.Id == groupId)
                    return groupInfo;
            }
            return null;
        }

        

        private void m_outputGrid_CellPainting(object sender, DataGridViewCellPaintingEventArgs e)
        {
            if (e.RowIndex == -1 && e.ColumnIndex >= 0)
            {
                e.PaintBackground(e.ClipBounds, true);
                Rectangle rect = e.CellBounds;
                Size titleSize = TextRenderer.MeasureText(e.Value.ToString(), e.CellStyle.Font);
                e.Graphics.TranslateTransform(0, titleSize.Width);
                e.Graphics.RotateTransform(-90.0F);
                e.Graphics.DrawString(e.Value.ToString(), e.CellStyle.Font, Brushes.Black, new PointF(titleSize.Width - m_outputGrid.ColumnHeadersHeight, rect.X));
                e.Graphics.RotateTransform(90.0F);
                e.Graphics.TranslateTransform(0, -titleSize.Width );
                e.Handled = true;
            }

        }

        private void admininstratorsToolStripMenuItem_Click(object sender, EventArgs e)
        {
            AdminUsersForm form = new AdminUsersForm(m_users);
            form.ShowDialog();
        }

        private void rbtnUsers_Click(object sender, EventArgs e)
        {
            ResetGrid(); 
            GatherUserGroupMembership();
            GatherACLs();
            m_users.Sort();

            FillGrid();
        }

        private void rbtnGroups_Click(object sender, EventArgs e)
        {
            ResetGrid();
            GatherGroupMembership();
            GatherACLs();
            m_groups.Sort();

            FillGrid();
        }

        private void m_outputGrid_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            
            if (e.RowIndex >= 0 && e.ColumnIndex >= 0 && allowedToClick)
            {
                SecurityService secSvc = webSericeManager.SecurityService;// (SecurityService)ServiceManager.GetService("SecurityService");
                AdminService adminSvc = webSericeManager.AdminService; // (AdminService)ServiceManager.GetService("AdminService");
                DocumentService docSvc = webSericeManager.DocumentService;// (DocumentService)ServiceManager.GetService("DocumentService");
                
                Folder[] folders = docSvc.FindFoldersByPaths(new string[1] { m_outputGrid.Columns[e.ColumnIndex].HeaderText});
                //User[] users = adminSvc.
                
                long groupUserID;
                int index = -1;
                
                if (rbtnGroups.Checked)
                {

                    GroupInfo group = m_groups.Find(
                        delegate(_GroupInfo gr)
                        {
                            return gr.Group.Name == m_outputGrid.Rows[e.RowIndex].HeaderCell.Value.ToString();
                        }
                    );
                    groupUserID = group.Group.Id;
                }
                else
                {
                    UserInfo user = m_users.Find(
                       delegate(_UserInfo ur)
                       {
                           return ur.User.Name == m_outputGrid.Rows[e.RowIndex].HeaderCell.Value.ToString();
                       }
                   );
                    groupUserID = user.User.Id;
                }


                long[] ids = new long[1];
                ids[0] = folders[0].Id;
                folderIdToModify = folders[0].Id;
                ACL[] acl = secSvc.GetACLsByEntityIds(ids);
                newACE = acl[0].ACEArray;

                AccessPermis[] permisArray = new AccessPermis[3];
                for (int i = 0; i < newACE.Length; i++)
                {
                    if (newACE[i].UserGrpId == groupUserID)
                    {
                        permisArray = newACE[i].PermisArray;
                        index = i;
                        //aceUpdated = true;
                    }
                }
                //need to modify this to actually collect the proper permissions and return the 
                //permission array

                p = new Permissions(permisArray, m_outputGrid.Rows[e.RowIndex].HeaderCell.Value.ToString(), m_outputGrid.Columns[e.ColumnIndex].HeaderText);
                p.Text = "Modify Permissions";
                p.ShowDialog();

                permisArray = p.SelectedPermissions;

                if (permisArray != null)
                {


                    if (index == -1)
                    {
                        newACE = new ACE[newACE.Length + 1];
                        acl[0].ACEArray.CopyTo(newACE, 0);
                        int lastItem = newACE.Length - 1;
                        newACE[lastItem] = new ACE();
                        newACE[lastItem].UserGrpId = groupUserID;
                        newACE[lastItem].PermisArray = permisArray;
                    }
                    else
                    {
                        newACE[index].PermisArray = permisArray;
                    }


                    KnowledgeVaultService knowSvc = webSericeManager.KnowledgeVaultService;// (KnowledgeVaultService)ServiceManager.GetService("KnowledgeVaultService");
                    toolStripProgressBar1.Maximum = int.Parse(knowSvc.GetExecutionTimeout().ToString());
                    
                    toolStripProgressBar1.Value = 0;
                    toolStripStatusLabel1.Text = "Updating Vault Please Wait";

                    backgroundWorker1.RunWorkerAsync();
                    timer1.Start();

                    

                    
                }
                //s = m_outputGrid.Rows[e.RowIndex].HeaderCell.Value.ToString();
                //s = m_outputGrid.Rows[e.RowIndex].Cells[e.ColumnIndex].Value.ToString();
               
            }
            
        }

        private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
        {

            allowedToClick = false;


            SecurityService secSvc = webSericeManager.SecurityService;// (SecurityService)ServiceManager.GetService("SecurityService");

            try
            {
                secSvc.UpdateACL(folderIdToModify, newACE, p.ApplyToChildren);
            }
            catch {
                MessageBox.Show("Server Time Out", "Error");
            
            }
            timer1.Stop();
        }

        private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
        {

        }

        private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            
            toolStripProgressBar1.Value = 1000; 
            toolStripStatusLabel1.Text = "Finished";
            
            GatherACLs();
            ResetGrid();
            FillGrid();
            //toolStripProgressBar1.Value = 0;
            //toolStripStatusLabel1.Text = "";
            
            allowedToClick = true;
        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            //TimeSpan ts = DateTime.Now.Subtract(startDate);

            //string sTime = "  ..." + ts.Minutes.ToString("00") +

            //   ":" + ts.Seconds.ToString("00") +

            //   ":" + ts.Milliseconds.ToString("000");

            //toolStripStatusLabelTime.Text = sTime;

            if (toolStripProgressBar1.Value !=

                toolStripProgressBar1.Maximum)
            {
                toolStripProgressBar1.PerformStep(); 
                //toolStripProgressBar1.Value = 0;

            }

            
        }
    }

    
}